<template>
	<view class="mainbgc">
		<header-top :messageInfo="{typeFlag:true,message:'打印机设置',liner:false}"></header-top>
		<view class="mainpadding2 margin_top ffffff">
			<view class="flexbetween needbotborder">
				<view class="strongtext">蓝牙打印</view>
				<u-switch v-model="mapvalue" activeColor="#61D671"></u-switch>
			</view>
			<template v-if="mapvalue">
				<view class="flexbetween needbotborder">
					<view class="strongtext">打印纸宽度</view>
					<view class="flexright">
						<view class="margin_box flexcenter">
							<text>80mm</text>
						</view>
						<!-- <view class="noselect margin_box flexcenter">
							<text>80mm</text>
						</view>
						<view class="noselect margin_box">58mm</view>
						<view class="select margin_box">
							<text>236mm</text>
							<view class="selectimage"></view>
						</view> -->
					</view>
				</view>
				<view class="flexbetween needbotborder">
					<view class="strongtext">打印机编码</view>
					<view class="nostrongtext">默认RGK</view>
				</view>
				<view class="needbotborder strongtext">已配对设备</view>
				<view class="flexleft needbotborder" v-for="(item,index) in ypd" :key="index"
					@click="createBLEConnection(item)">
					<view class="selecticon margin_right" v-if="item.target.dataset.title==deviceId">
						<image src="@/static/image/system/dui.png" mode=""></image>
					</view>
					<view class="nostrongtext">
						{{item.target.dataset.name}}({{item.target.dataset.title==deviceId?"已连接":"已配对"}})</view>
				</view>
			</template>
		</view>
		<template v-if="mapvalue">
			<view class="mainpadding_top ffffff paddingbom">
				<view class="strongtext">发现新设备</view>
				<!-- <view class="needbotborder nostrongtext" v-for="(item,index) in lyarr" :key="index"
					@click="createBLEConnection(item)">{{item.name}}</view> -->
				<view class="needbotborder nostrongtext" v-for="(item,index) in list" :data-title="item.deviceId"
					:data-name="item.name" :data-advertisData="item.advertisServiceUUIDs" :key="item.deviceId"
					@tap="bindViewTap">{{item.name}}</view>
			</view>
			<!-- <view class="yesbtn" @click="startBluetoothDevicesDiscovery(1)">
				搜索
			</view> -->
			<view class="yesbtn" @click="startSearch">搜索</view>
		</template>
		<!-- <view class="content">
			<button class="btn" type="primary" :loading="isSearching" @tap="startSearch">开始搜索 </button>
			<button class="btn" type="warn" @tap="stopSearch">停止搜索</button>
			<view v-for="(item) in list" :data-title="item.deviceId" :data-name="item.name" :data-advertisData="item.advertisServiceUUIDs"
			 :key="item.deviceId" @tap="bindViewTap">
				<view class="item">
					<view class="deviceId block">{{item.deviceId}}</view>
					<view class="name block">{{item.name}}</view>
				</view>
			</view>
		</view> -->
	</view>
</template>

<script>
	const httpRequest = require("@/common/httpRequest.js")
	import {
		mapState
	} from 'vuex';
	export default {
		data() {
			return {
				mapvalue: true,
				lyarr: [],
				ypd: [], //已配对内容
				deviceId: '', //设备蓝牙deviceId
				// services: '', //蓝牙的uuid
				notifyId: '', //开启notify接收
				writeId: '', //接收写入的值
				// 打印机参数
				isSearching: false, //是否正在搜索中
				list: [],
				services: [],
				serviceId: 0,
				writeCharacter: false,
				readCharacter: false,
				notifyCharacter: false
			}
		},
		computed: mapState(['sysinfo', 'Bluetooth']),
		onUnload() {
			//停止搜索蓝牙设备
			if (this.isSearching) {
				uni.stopBluetoothDevicesDiscovery();
			}
		},
		onLoad() {
			this.startSearch()
			// let _this = this
			// uni.getStorage({
			// 	key:'ypd',
			// 	success(res) {
			// 		_this.ypd = res.data;
			// 	}
			// });
			// this.openBluetoothAdapter()
		},

		// watch: {
		// 	mapvalue(newval) {
		// 		if (newval) {
		// 			this.openBluetoothAdapter()
		// 		}
		// 	},
		// 	ypd(newval){
		// 		let _this = this
		// 		uni.setStorageSync('ypd',this.ypd);
		// 	}
		// },
		methods: {
			
			// // 打开蓝牙适配器
			// openBluetoothAdapter() {
			// 	uni.openBluetoothAdapter({
			// 		success: res => {
			// 			this.startBluetoothDevicesDiscovery();
			// 		},
			// 		fail: res => {
			// 			if (res.errCode === 10001) {
			// 				httpRequest.toast("请打开蓝牙")
			// 				uni.onBluetoothAdapterStateChange(res => {
			// 					if (res.available) {
			// 						this.startBluetoothDevicesDiscovery();
			// 					}
			// 				});
			// 			}
			// 		}
			// 	});
			// },
			// // 开启蓝牙搜索
			// startBluetoothDevicesDiscovery(value) {
			// 	if(value==1){
			// 		uni.showLoading({
			// 			title: '请稍候...',
			// 			mask:true
			// 		})
			// 	}
			// 	uni.startBluetoothDevicesDiscovery({
			// 		allowDuplicatesKey: false,
			// 		success: res => {
			// 			this.onBluetoothDeviceFound();
			// 			setTimeout(()=>{
			// 				uni.hideLoading()
			// 				this.stopBluetoothDevicesDiscovery()
			// 			},1500)
			// 		}
			// 	});

			// },
			// // 监听蓝牙设备列表获取蓝牙设备列表
			// onBluetoothDeviceFound() {
			// 	uni.onBluetoothDeviceFound(res => {
			// 		//console.log(res,"999")
			// 		let num = 0
			// 		this.lyarr.forEach(item => {
			// 			if (item.name != res.devices[0].name) {
			// 				num = num + 1
			// 			}
			// 		})
			// 		if (num == this.lyarr.length && res.devices[0].name != "") {
			// 			this.lyarr.push(res.devices[0])
			// 		}

			// 	});

			// },
			// // 建立连接
			// createBLEConnection(device) {
			// 	let _this = this
			// 	//console.log(device, "device当前对象")
			// 	const deviceId = device.deviceId;
			// 	uni.showLoading({
			// 		title: '请稍候...',
			// 		mask:true
			// 	})
			// 	// 断开连接
			// 	uni.closeBLEConnection({
			// 	  deviceId:_this.deviceId,
			// 	  success(res) {
			// 	    //console.log(res,"断开连接")
			// 	  }
			// 	})
			// 	// 连接
			// 	uni.createBLEConnection({
			// 		deviceId,
			// 		success: res => {
			// 			uni.hideLoading()
			// 			this.deviceId = deviceId
			// 			this.getConnectedBluetoothDevices(device.advertisServiceUUIDs);
			// 		},fail(err) {
			// 			uni.hideLoading()
			// 			if(err.errCode==10012){
			// 				httpRequest.toast("连接超时,请重试")
			// 			}else {
			// 				httpRequest.toast("连接失败,请重试")
			// 			}
			// 			//console.log(err,"错误信息")
			// 		}
			// 	});
			// },
			// // 停止蓝牙搜搜
			// stopBluetoothDevicesDiscovery() {
			// 	//console.log("终止")
			// 	uni.stopBluetoothDevicesDiscovery();
			// },
			// // 获取蓝牙设备服务
			// getConnectedBluetoothDevices(services) {
			// 	uni.getConnectedBluetoothDevices({
			// 		services,
			// 		success: res => {
			// 			//console.log(res,2372934)
			// 			let flag = false
			// 			this.ypd.forEach(item=>{
			// 				if(item.deviceId==res.devices[0].deviceId){
			// 					flag = true
			// 				}
			// 			})
			// 			if(!flag){
			// 				this.ypd.push(res.devices[0])
			// 			}
			// 		}
			// 	});

			// },
			// 打印机内容开始
			//错误码提示
			errorCodeTip(code) {
				if (code == 0) {
					//正常
				} else if (code == 10000) {
					uni.showToast({
						title: '未初始化蓝牙适配器',
						icon: 'none'
					})
				} else if (code == 10001) {
					uni.showToast({
						title: '当前蓝牙适配器不可用',
						icon: 'none'
					})
				} else if (code == 10002) {
					uni.showToast({
						title: '没有找到指定设备',
						icon: 'none'
					})
				} else if (code == 10003) {
					uni.showToast({
						title: '连接失败',
						icon: 'none'
					})
				} else if (code == 10004) {
					uni.showToast({
						title: '没有找到指定服务',
						icon: 'none'
					})
				} else if (code == 10005) {
					uni.showToast({
						title: '没有找到指定特征值',
						icon: 'none'
					})
				} else if (code == 10006) {
					uni.showToast({
						title: '当前连接已断开',
						icon: 'none'
					})
				} else if (code == 10007) {
					uni.showToast({
						title: '当前特征值不支持此操作',
						icon: 'none'
					})
				} else if (code == 10008) {
					uni.showToast({
						title: '其余所有系统上报的异常',
						icon: 'none'
					})
				} else if (code == 10009) {
					uni.showToast({
						title: 'Android 系统特有，系统版本低于 4.3 不支持 BLE',
						icon: 'none'
					})
				}
			},
			//开始搜索蓝牙
			startSearch() {
				let that = this
				uni.openBluetoothAdapter({
					success(res) {
						uni.getBluetoothAdapterState({
							success(res2) {
								// //console.log('getBluetoothAdapterState:', res2)
								if (res2.available) {
									that.isSearching = true;
									console.log(res2,"惊雷惊雷惊雷")
									if (res2.discovering) {
										uni.showToast({
											title: '正在搜索附近打印机设备',
											icon: "none"
										})
										return;
									}
									//获取蓝牙设备信息
									that.getBluetoothDevices()
									// that.checkPemission()
								} else {
									uni.showModal({
										title: '提示',
										content: '本机蓝牙不可用',
									})
								}
							}
						});
					},
					fail() {
						uni.showModal({
							title: '提示',
							content: '蓝牙初始化失败，请打开蓝牙',
						})
					}
				})
			},
			stopSearch() {
				uni.stopBluetoothDevicesDiscovery({
					success: (res) => {
						this.isSearching = false;
						// //console.log('stop:', res)
					},
					fail: (e) => {
						// //console.log('stop:', e)
						this.errorCodeTip(e.errCode);
					}
				})
			},
			//校验权限
			checkPemission() {
				let that = this
				let {
					BLEInformation
				} = that.Bluetooth;
				let platform = BLEInformation.platform;
				that.getBluetoothDevices();
			},
			//获取蓝牙设备信息
			getBluetoothDevices() {
				let that = this
				that.list = [];
				console.log(11111111,"金戈里")
				uni.startBluetoothDevicesDiscovery({
					success(res) {
						console.log(res)
						//蓝牙设备监听 uni.onBluetoothDeviceFound
						plus.bluetooth.onBluetoothDeviceFound((result) => {
							console.log('onBluetoothDeviceFound:', result)
							let arr = that.list;
							let devices = [];
							let list = result.devices;
							for (let i = 0; i < list.length; ++i) {
								if (list[i].name && list[i].name != "未知设备") {
									let arrNew = arr.filter((item) => {
										return item.deviceId == list[i].deviceId;
									});
									// //console.log('arrNew:',arrNew.length)
									if (arrNew.length == 0) {
										devices.push(list[i]);
									}
								}
							}

							that.list = arr.concat(devices);
						});
						that.time = setTimeout(() => {
							// uni.getBluetoothDevices
							plus.bluetooth.getBluetoothDevices({
								success(res2) {
									let devices = [];
									let list = res2.devices;
									for (let i = 0; i < list.length; ++i) {
										if (list[i].name && list[i].name != "未知设备") {
											devices.push(list[i]);
										}
									}
									that.list = devices;
									console.log('getBluetoothDevices:', res2);
								},
							})

							clearTimeout(that.time);
						}, 3000);
					}
				});

			},
			//绑定蓝牙
			bindViewTap(e) {
				// //console.log(e, "当前对象")
				let that = this;
				let {
					title
				} = e.currentTarget.dataset;
				let {
					BLEInformation
				} = that.Bluetooth;
				this.stopSearch();

				that.serviceId = 0;
				that.writeCharacter = false;
				that.readCharacter = false;
				that.notifyCharacter = false;
				uni.showLoading({
					title: '正在连接',
				})
				// //console.log('deviceId:', title)
				// uni.createBLEConnection
				plus.bluetooth.createBLEConnection({
					deviceId: title,
					success(res) {
						let flag = false
						that.ypd.forEach(item => {
							if (item.target.dataset.title == e.target.dataset.title) {
								flag = true
							}
						})
						if (!flag) {
							that.ypd.push(e)
						}
						that.deviceId = e.target.dataset.title
						// //console.log('createBLEConnection success:', res)
						BLEInformation.deviceId = title;
						that.$store.commit('BLEInformationSet', BLEInformation);
						uni.hideLoading()
						that.getSeviceId()
					},
					fail(e) {
						that.errorCodeTip(e.errCode);
						uni.hideLoading()
					}
				})
			},
			//获取蓝牙设备所有服务(service)。
			getSeviceId() {
				let that = this;
				let {
					BLEInformation
				} = that.Bluetooth;
				// //console.log('BLEInformation.deviceId:', BLEInformation.deviceId)
				// uni.getBLEDeviceServices
				let t = setTimeout(() => {
					plus.bluetooth.getBLEDeviceServices({
						deviceId: BLEInformation.deviceId,
						success(res) {
							// //console.log('getBLEDeviceServices success:', res)
							that.services = res.services;
							that.getCharacteristics()
						},
						fail: function(e) {
							that.errorCodeTip(e.code);
							// //console.log('getBLEDeviceServices fail:', e)
						}
					})
					clearTimeout(t);
				}, 1500)
			},
			getCharacteristics() {
				var that = this
				let {
					services: list,
					serviceId: num,
					writeCharacter: write,
					readCharacter: read,
					notifyCharacter: notify
				} = that;
				let {
					BLEInformation
				} = that.Bluetooth;
				// uni.getBLEDeviceCharacteristics
				plus.bluetooth.getBLEDeviceCharacteristics({
					deviceId: BLEInformation.deviceId,
					serviceId: list[num].uuid,
					success(res) {
						// //console.log(res)
						for (var i = 0; i < res.characteristics.length; ++i) {
							var properties = res.characteristics[i].properties
							var item = res.characteristics[i].uuid
							if (!notify) {
								if (properties.notify) {
									BLEInformation.notifyCharaterId = item;
									BLEInformation.notifyServiceId = list[num].uuid;
									that.$store.commit('BLEInformationSet', BLEInformation);
									notify = true
								}
							}
							if (!write) {
								if (properties.write) {
									BLEInformation.writeCharaterId = item;
									BLEInformation.writeServiceId = list[num].uuid;
									that.$store.commit('BLEInformationSet', BLEInformation);
									write = true
								}
							}
							if (!read) {
								if (properties.read) {
									BLEInformation.readCharaterId = item;
									BLEInformation.readServiceId = list[num].uuid;
									that.$store.commit('BLEInformationSet', BLEInformation);
									read = true
								}
							}
						}
						if (!write || !notify || !read) {
							num++
							that.writeCharacter = write;
							that.readCharacter = read;
							that.notifyCharacter = notify;
							that.serviceId = num;
							if (num == list.length) {
								uni.showModal({
									title: '提示',
									content: '找不到该读写的特征值',
								})
							} else {
								that.getCharacteristics()
							}
						}
					},
					fail: function(e) {
						// //console.log("getBLEDeviceCharacteristics fail：", e);
						that.errorCodeTip(e.errCode);
					}
				})
			},
		}
	}
</script>

<style>
	.needbotborder {
		padding: 30rpx 0;
		border-bottom: 1rpx solid rgba(153, 153, 153, 0.05);
	}

	.needbotborder:last-child {
		padding: 30rpx 0 0;
		border-bottom: none;
	}

	/* 未选中状态 */
	.noselect {
		font-size: 24rpx;
		font-weight: 500;
		color: #000000;
		border-radius: 10rpx;
		border: 1rpx solid #999999;
		padding: 6rpx 16rpx;
	}

	/* 选中状态 */
	.select {
		position: relative;
		font-size: 24rpx;
		font-weight: 500;
		color: #0BBDCB;
		background-color: #e7f9fa;
		padding: 6rpx 16rpx;
		border-radius: 10rpx;
		border: 1rpx solid #0BBDCB;
	}

	.margin_box {
		margin-right: 5rpx;
	}

	.margin_box:last-child {
		margin-right: 0;
	}
</style>
